﻿using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using ICell = NPOI.SS.UserModel.ICell;

namespace GBT_Tool
{
    public class ExportExcel
    {
        public void ExportMealReportToExcel(JArray jaMealReport, string path, string hallName, string mealName, string date)
        {
            try
            {
                //创建Excel文件的对象
                HSSFWorkbook book = new HSSFWorkbook();
                //添加一个sheet
                ISheet sheet = book.CreateSheet($"每日报餐明细");

                //行下标记录
                int rowIndex = 0;
                //创建首行
                IRow rowHall = sheet.CreateRow(rowIndex);
                //创建单元格
                ICell cellHall = rowHall.CreateCell(0);
                //设置单元格内容
                cellHall.SetCellValue("食堂");
                ICell cellHallValue = rowHall.CreateCell(1);
                cellHallValue.SetCellValue(hallName);

                IRow rowMeal = sheet.CreateRow(++rowIndex);
                ICell cellMeal = rowMeal.CreateCell(0);
                cellMeal.SetCellValue("餐点");
                ICell cellMealValue = rowMeal.CreateCell(1);
                cellMealValue.SetCellValue(mealName);

                IRow rowDate = sheet.CreateRow(++rowIndex);
                ICell cellDate = rowDate.CreateCell(0);
                cellDate.SetCellValue("日期");
                ICell cellDateValue = rowDate.CreateCell(1);
                cellDateValue.SetCellValue(date);

                IRow rowList = sheet.CreateRow(++rowIndex);
                ICell cellList1 = rowList.CreateCell(0);
                cellList1.SetCellValue("工号");
                ICell cellList2 = rowList.CreateCell(1);
                cellList2.SetCellValue("姓名");
                ICell cellList3 = rowList.CreateCell(2);
                cellList3.SetCellValue("数量");
                ICell cellList4 = rowList.CreateCell(3);
                cellList4.SetCellValue("单位");

                //创建多行
                for (int mealReportIndex = 0; mealReportIndex < jaMealReport.Count; mealReportIndex++)
                {
                    var row = sheet.CreateRow(++rowIndex);

                    //连写创建单元格并设置单元格内容 （一般这样写更好点）
                    row.CreateCell(0).SetCellValue(jaMealReport[mealReportIndex]["number"].ToString());
                    row.CreateCell(1).SetCellValue(jaMealReport[mealReportIndex]["name"].ToString());
                    row.CreateCell(2).SetCellValue(jaMealReport[mealReportIndex]["qty"].ToString());
                    row.CreateCell(3).SetCellValue("份");
                }

                using (FileStream st = new FileStream(path, FileMode.OpenOrCreate))
                {
                    book.Write(st);
                }
            }
            catch
            {
                throw;
            }
        }
    }
}
